package day02;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoAccessLog extends HttpServlet{
	private String dateFormat;
	private String logFile;
	
	@Override
	public void init() throws ServletException {
		ServletConfig config = getServletConfig();
		String longFile = config.getInitParameter("logFile");
		String dareFormat = config.getInitParameter("dateFormat");
		
		System.out.println(longFile);
		System.out.println(dareFormat);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println(req.getRemoteAddr());
		Date date = new Date();
		System.out.println(date);
		System.out.println("有人访问了。。");
		
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		String content = req.getRemoteAddr()+"\t"+formatter.format(date);
		logFile(content);
	}
	
	private void logFile(String content) {
	  try (BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\acccess1.log",true));){
		writer.write(content);
		writer.write("\n");
		writer.flush();
	} catch (IOException e) {
		e.printStackTrace();
	}
	}
}
